package com.feidee.bigdata.controller;

import com.feidee.bigdata.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @Author:CHQ
 * @Date:2020/4/14 18:26
 * @Description
 */
@RestController
public class PaymentHystrixController {

    @Autowired
    private PaymentService paymentService;


    @RequestMapping("/ok")
    public String ok() throws InterruptedException {
        return paymentService.ok();
    }

    @RequestMapping("/err")
    public String error() {
        return paymentService.error();
    }

    @RequestMapping("/testBreak/{id}")
    @HystrixCommand(fallbackMethod = "testBreakHandel",
            commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), //熔断服务是否开启
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), //请求次数
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //时间范围
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")}) //失败率
    public String testBreak(@PathVariable("id") Long id) {
        if (id < 0) {
            throw new RuntimeException("id不能为负数");
        }
        return "恭喜调用成功,此次服务的流水号为：" + UUID.randomUUID().toString();
    }

    //此处方法的参数不可不传，必须需要降级的方法保持一致,否则报错
    public String testBreakHandel(@PathVariable("id") Long id) {
        return "本次请求id：" + id + " 正在进行服务熔断，请稍后重试~";
    }

}
